package pl.un4giv3n.mightvsmagic.action;

import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.Action;
import pl.un4giv3n.mightvsmagic.entity.ActionType;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.Item;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActionUtil;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

/**
 * @author andrzejewskia
 * sell user item action
 */
public class SellAction extends BazarPageAction {

	private static final long serialVersionUID = 1L;
	/**
	 *  sold item id
	 */
	private long itemId;
	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		Action currentAction = user.getCurrentAction();
		if (currentAction == null || currentAction.equals(Action.NO_ACTION) || currentAction.getActionType().equals(ActionType.FIGHT)) {
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			Item item = entityManager.find(Item.class, itemId);
			if(item == null){
				transaction.rollback();
				prepareEq(entityManager);
				entityManager.close();
				addActionError("Nie znaleziono przedmiotu do sprzedaży");
				return INPUT;
			}
			for (Iterator<Item> iterator = user.getItems().iterator(); iterator.hasNext();) {
				Item it = iterator.next();
				if(it.getId().longValue() == item.getId().longValue()){
					iterator.remove();
					break;
				}
				
			}
			user.addGold(item.getPrice()/30);
			user.setDragonTeeth(user.getDragonTeeth() + item.getPremiumPrice()/30);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.ITEM_SOLD, user.getId(), "Sprzedany przedmiot: "+item.toString());
			entityManager.persist(activity);
			entityManager.remove(item);
			entityManager.merge(user);
			entityManager.flush();
			transaction.commit();
			entityManager.close();
			addActionMessage("Dokonałeś zakupu przedmiotu!");
			//set this to redirect to right bazar tab
			selectedType = item.getType();
			return SUCCESS;
		} else {
			prepareEq(entityManager);
			entityManager.close();
			addActionError(ActionUtil.generateErrorMessage(currentAction, user));
			return INPUT;
		}
	}

	public long getItemId() {
		return itemId;
	}

	public void setItemId(long itemId) {
		this.itemId = itemId;
	}
	
}
